<route lang="json5" type="page">
{
  "needLogin": true,
  style: {
    navigationBarTitleText: '报修记录',
    enablePullDownRefresh: true,
  },
}
</route>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

// 定义报修记录的类型
interface Record {
  id: number
  date: string
  problem: string
  household: string
  contact: string
  status: '已处理' | '待处理'
  images?: string[]
}

type LoadMoreStatus = 'more' | 'loading' | 'noMore'

const recordList = ref<Record[]>([])
const loadingStatus = ref<LoadMoreStatus>('more')
const page = ref(1)
const pageSize = 10
const initialLoading = ref(true)

const wdState = computed<'loading' | 'finished' | null>(() => {
  if (loadingStatus.value === 'loading') {
    return 'loading'
  }
  if (loadingStatus.value === 'noMore') {
    return recordList.value.length > 0 ? 'finished' : null
  }
  return null
})

// 模拟的报修数据
const mockRecords: Record[] = [
  { id: 1, date: '2023.06.06', problem: '水表漏水', household: '501', contact: '16666666666', status: '已处理', images: ['https://picsum.photos/seed/1/200/200', 'https://picsum.photos/seed/2/200/200'] },
  { id: 2, date: '2023.06.06', problem: '频繁跳闸', household: '502', contact: '16666666666', status: '待处理', images: [] },
  { id: 3, date: '2023.06.06', problem: '电表烧坏', household: '501', contact: '16666666666', status: '待处理', images: ['https://picsum.photos/seed/3/200/200'] },
  { id: 4, date: '2023.06.05', problem: '下水道堵塞', household: '301', contact: '16666666666', status: '已处理', images: ['https://picsum.photos/seed/4/200/200', 'https://picsum.photos/seed/5/200/200', 'https://picsum.photos/seed/6/200/200'] },
  { id: 5, date: '2023.06.05', problem: '门禁失灵', household: '102', contact: '16666666666', status: '待处理' },
  { id: 6, date: '2023.06.04', problem: '电梯异响', household: '公共区域', contact: '16666666666', status: '已处理', images: ['https://picsum.photos/seed/7/200/200'] },
]

// 模拟获取报修记录数据
async function fetchRecords(pageNum: number, num: number): Promise<Record[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      const start = (pageNum - 1) * num
      const end = start + num
      const data = mockRecords.slice(start, end)
      resolve(data)
    }, 800)
  })
}

// 加载报修记录
async function loadRecords(reload = false) {
  if (reload) {
    page.value = 1
  }

  if (loadingStatus.value === 'noMore' && !reload)
    return

  loadingStatus.value = 'loading'

  try {
    const res = await fetchRecords(page.value, pageSize)
    if (reload) {
      recordList.value = []
    }

    if (res.length > 0) {
      recordList.value.push(...res)
      page.value++
      loadingStatus.value = 'more'
    }
    else {
      loadingStatus.value = 'noMore'
    }
  }
  catch (error) {
    console.error('Failed to fetch records:', error)
    loadingStatus.value = 'more' // Reset status on error
  }
  finally {
    if (initialLoading.value) {
      initialLoading.value = false
    }
    uni.stopPullDownRefresh()
  }
}

onLoad(() => {
  loadRecords(true)
})

// 下拉刷新
onPullDownRefresh(async () => {
  await loadRecords(true)
})

// 上拉加载
onReachBottom(() => {
  loadRecords()
})

function getStatusClass(status: '已处理' | '待处理') {
  return status === '已处理' ? 'text-green-500' : 'text-orange-500'
}

function previewImage(imageUrls: string[], current: number) {
  uni.previewImage({
    urls: imageUrls,
    current,
  })
}

function handleToRepair() {
  uni.navigateTo({
    url: '/pages-user/user/repair/index',
  })
}
</script>

<template>
  <view class="record-page pt-4 pb-safe">
    <view class="mb-3 flex justify-end pr-3">
      <wd-button size="small" @click="handleToRepair">
        我要报修
      </wd-button>
    </view>

    <!-- 无数据提示 -->
    <view v-if="recordList.length === 0" class="pt-10 text-center text-gray-500">
      <wd-status-tip image="search" tip="暂无报修记录" />
    </view>

    <!-- 记录列表 -->
    <template v-else>
      <wd-card v-for="record in recordList" :key="record.id" class="mb-3">
        <view class="py-4 text-sm">
          <view class="flex items-center justify-between">
            <view>
              <text class="text-gray-500">
                日期：
              </text>
              <text>{{ record.date }}</text>
            </view>
            <view>
              <text class="font-bold" :class="getStatusClass(record.status)">
                {{ record.status }}
              </text>
            </view>
          </view>

          <view class="mt-2">
            <text class="text-gray-500">
              报修问题：
            </text>
            <text>{{ record.problem }}</text>
          </view>

          <view class="mt-2">
            <text class="text-gray-500">
              户号：
            </text>
            <text>{{ record.household }}</text>
          </view>

          <view class="mt-2">
            <text class="text-gray-500">
              紧急联系人：
            </text>
            <text>{{ record.contact }}</text>
          </view>

          <view v-if="record.images && record.images.length > 0" class="mt-2">
            <view class="mb-2 text-gray-500">
              上传图片：
            </view>
            <view class="flex flex-wrap gap-2">
              <image
                v-for="(img, index) in record.images"
                :key="index"
                :src="img"
                class="h-20 w-20 rounded"
                mode="aspectFill"
                lazy-load
                @click="previewImage(record.images, index)"
              />
            </view>
          </view>
        </view>
      </wd-card>
    </template>

    <!-- 加载更多 -->
    <wd-loadmore v-if="!initialLoading && wdState" :state="wdState" />
  </view>
</template>

<style lang="scss" scoped>
.record-page {
  box-sizing: border-box;
}
</style>
